package com.jason.system.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author jie
 * @version 1.0
 * success come from self-discipline
 * @date 2021/4/11 23:28
 */

@Component
public class RedisUtil {

  private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

  @Autowired
  private RedisTemplate<String, Object> redisTemplate;

  /**
   * 写入redis缓存，不设置expire时间
   * @param key 键
   * @param value object对象
   * @return true or false
   */
  public boolean set(String key, Object value){
    try {
      redisTemplate.opsForValue().set(key,value);
      return true;
    }catch (Exception e){
      logger.info("写入redis缓存失败！失败信息为: {}",e.getMessage());
      return false;
    }
  }

  /**
   * 写入redis缓存，添加expire过期时间
   * @param key 键
   * @param value Object对象
   * @param expire 过期时间
   * @return true or false
   */
  public boolean set(String key, Object value, long expire){
    try {
      if (expire > 0) {
        redisTemplate.opsForValue().set(key, value, expire, TimeUnit.MINUTES);
      }else {
        set(key,value);
      }
      return true;
    }catch (Exception e){
      logger.info("写入redis缓存失败！失败信息为: {}",e.getMessage());
      return false;
    }
  }

  /**
   * 判断是否存在key
   * @param key 键
   * @return true or false
   */
  public boolean hasKey(String key){
    boolean result = false;
    try {
      result = redisTemplate.hasKey(key);
    }catch (Exception e){
      logger.info("查询是否存在key失败！");
    }
    return result;
  }

  /**
   * redis根据key删除对应value
   * @param key
   * @return
   */
  public boolean remove(String key){
    boolean result = false;
    try {
      if (hasKey(key)){
        redisTemplate.delete(key);
      }
      result = true;
    }catch (Exception e){
      logger.info("根据key删除对应value失败: {}",e.getMessage());
    }
    return result;
  }

  /**
   * redis根据keys批量删除对应value
   * @param keys key集合
   */
  public void remove(List<String> keys){
    try {
      redisTemplate.delete(keys);
    }catch (Exception e){
      logger.info("根据keys批量删除对应value失败: {}",e.getMessage());
    }
  }

  /**
   * 读取redis缓存
   * @param key
   * @return Object
   */
  public Object get(String key){
    Object o = new Object();
    try {
      o = redisTemplate.opsForValue().get(key);
    }catch (Exception e){
      logger.info("读取redis缓存失败: {}",e.getMessage());
    }
    return o;
  }

  /**
   * 将list缓存进redis
   * @param key 键
   * @param value list对象
   * @return true or false
   */
  public boolean lset(String key, Object value){
    try {
      redisTemplate.opsForList().rightPush(key,value);
      return true;
    }catch (Exception e){
      logger.info("以list缓存进redis失败: {}",e.getMessage());
      return false;
    }
  }

}
